/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cinema.client.cinemaclient.managers;

import com.cinema.client.cinemaclient.constants.Constants;
import com.cinema.client.cinemaclient.model.User;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 *
 * @author Zsolt Szecsi
 */
public class UserManager {

    public User insertUser(User user) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Users");

        return target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(user, MediaType.APPLICATION_JSON), User.class);
    }

    public User updateUser(User user) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(Constants.BASE_URL + "Users");

        return target.request(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity(user, MediaType.APPLICATION_JSON), User.class);
    }

    public User getUserByUsername(String username) {
        try {
            Client client = ClientBuilder.newClient();
            WebTarget target = client.target(Constants.BASE_URL + "Users/" + username);
            User movieResponse = null;
            Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get();
            if (response != null && Response.Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily()) {
                movieResponse = response.readEntity(User.class);
                return movieResponse;
            } else {
                System.err.println("There was an error fetching service response");
                System.err.println(response);
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

}
